<template>
  <div class="timeline">
    <input type="button" value="<" @mousedown="leftDownFn" @mouseup="leftUpFn">
    <div class="timelineBox" @mouseenter="enterFn" @mouseleave="leaveFn" :style="{width:boxW+'px'}">
      <div
        class="container"
        :style="{left:left+'px', width:width+'px'}"
      >
        <div class="item" v-for="item in data" :key="item.id" :style="{width: oneItemW+'px'}">
          <div class="item_cont">{{ item.msg.a }}</div>
        </div>
      </div>
    </div>
    <input type="button" value=">" @mousedown="rightDownFn" @mouseup="rightUpFn">
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';

const data = reactive([
  {
    id:"1",
    msg:{
      a:"2001",b:"",c:""
    }
  },
  {
    id:"2",
    msg:{
      a:"2002",b:"",c:""
    }
  },
  {
    id:"3",
    msg:{
      a:"2003",b:"",c:""
    }
  },
  {
    id:"4",
    msg:{
      a:"2004",b:"",c:""
    }
  },
  {
    id:"5",
    msg:{
      a:"2005",b:"",c:""
    }
  },
  {
    id:"6",
    msg:{
      a:"2006",b:"",c:""
    }
  },
  {
    id:"7",
    msg:{
      a:"2007",b:"",c:""
    }
  },
  {
    id:"8",
    msg:{
      a:"2008",b:"",c:""
    }
  },
  {
    id:"9",
    msg:{
      a:"2009",b:"",c:""
    }
  },
  {
    id:"10",
    msg:{
      a:"2010",b:"",c:""
    }
  },
  {
    id:"1",
    msg:{
      a:"2001",b:"",c:""
    }
  },
  {
    id:"2",
    msg:{
      a:"2002",b:"",c:""
    }
  },
  {
    id:"3",
    msg:{
      a:"2003",b:"",c:""
    }
  },
  {
    id:"4",
    msg:{
      a:"2004",b:"",c:""
    }
  },
]);

// 视口容器宽度
const boxW = ref(1200);
// 单个项目宽度
const oneItemW = ref(300);
// 项目容器宽度
const width = ref( data.length * (oneItemW.value) );
// 项目容器left
const left = ref(0);

// 初始步长
const speed = ref(2);

// 运动
function move(){
  left.value -= speed.value;
  if(speed.value > 0 && left.value <= -(data.length-(boxW.value/oneItemW.value))*oneItemW.value){
    left.value = 0;
  }
  if(speed.value < 0 && left.value >= 0){
    left.value = -(data.length-(boxW.value/oneItemW.value))*oneItemW.value;
  }
}

// 开始运动
let t = setInterval(move, 30);

// 方向和加速
function leftDownFn(){
  speed.value = -16;
}
function leftUpFn(){
  speed.value = -2;
}
function rightDownFn(){
  speed.value = 16;
}
function rightUpFn(){
  speed.value = 2;
}
// 进入和离开
function enterFn(){
  clearInterval(t)
}
function leaveFn(){
  t = setInterval(move, 30);
}

</script>

<style scoped>
.timeline{
  width:1300px;
  margin: 0 auto;
  background: #ccc;
  padding: 20px;
  display: flex;
}
.timeline .timelineBox{
  height:200px;
  margin: 0 auto;
  position:relative;
  background: #fff;
  padding: 10px 0;
  overflow: hidden;
}
.timeline .timelineBox .container{
  position: absolute;
}
.timeline .timelineBox .item{
  float: left;
  padding: 0 10px;
  box-sizing: border-box;
}
.timeline .timelineBox .item_cont{
  background: pink;
  font-size: 30px;line-height: 200px;
  text-align: center;
  height: 200px;
}
</style>